package com.killer_jin.core.common.handler;

import com.killer_jin.core.common.exception.AuthFaildException;
import com.killer_jin.core.common.util.ErrorUtil;
import com.killer_jin.core.common.util.ResponseErrorUtils;
import com.killer_jin.core.common.util.vo.Result;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by Frank Wu on 16/4/29.
 * 这是一个controller增强处理器
 * @ ControllerAdvice(@RestControllerAdvice可以返回ResponseBody)，可看做Controller增强器，可以在@ControllerAdvice作用类下
 * 添加@ExceptionHandler，@InitBinder，@ModelAttribute注解的方法来增强Controller，都会作用在被 @RequestMapping 注解的方法上。
 */
@ControllerAdvice
public class GlobalDefaultExceptionHandler {
    public static final String DEFAULT_ERROR_VIEW = "error";

    /**
     * 参数校验异常
     * @ ExceptionHandler的作用主要在于声明一个或多个类型的异常，当符合条件的Controller抛出这些异常之后将会对这些异常进行捕获，
     * 然后按照其标注的方法的逻辑进行处理，从而改变返回的视图信息。
     * @param e 参数校验异常
     * @return HttpStatus 400 返回参数错误信息
     */
    @ExceptionHandler(value = BindException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public Result bindExceptionHandler(BindException e) {
        FieldError fieldError = e.getBindingResult().getFieldError();
        assert fieldError != null;
        String defaultMessage = fieldError.getDefaultMessage();
        return Result.genFail(defaultMessage);
    }

    /**
     * 参数校验异常
     *
     * @param e 参数校验异常
     * @return HttpStatus 400 返回参数错误信息
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public Result methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        FieldError fieldError = e.getBindingResult().getFieldError();
        assert fieldError != null;
        String defaultMessage = fieldError.getDefaultMessage();
        return Result.genFail(defaultMessage);
    }

    /**
     * 权限错误
     *
     * @param e AuthFailedException
     * @return HttpStatus 403 授权异常
     */
    @ExceptionHandler(value = AuthFaildException.class)
    @ResponseStatus(HttpStatus.FORBIDDEN)
    @ResponseBody
    public Result authFailedExceptionHandler(AuthFaildException e) {
        return Result.genFail(ErrorUtil.getMsg(e));
    }


    @ExceptionHandler(value = Exception.class)
    public ModelAndView defaultErrorHandler(HttpServletRequest req, HttpServletResponse resp, Exception e) throws Exception {
        if (!(e instanceof AuthFaildException)) {
            e.printStackTrace();
        }

        // If the exception is annotated with @ResponseStatus rethrow it and let
        // the framework handle it - like the OrderNotFoundException example
        // at the start of this post.
        // AnnotationUtils is a Spring Framework utility class.
        if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null) {
            throw e;
        }

        String requestURL = req.getRequestURL().toString();
        if (requestURL.indexOf(".json") > -1 || requestURL.indexOf("/api") > -1) {
            if (e instanceof AuthFaildException) {
                ResponseErrorUtils.sendJsonError(403, ErrorUtil.getMsg(e), resp);
            } else {
                ResponseErrorUtils.sendJsonError(500, ErrorUtil.getMsg(e), resp);
            }
            return null;
        }

        // Otherwise setup and send the user to a default error-view.
        ModelAndView mav = new ModelAndView();
        mav.addObject("message", ErrorUtil.getMsg(e));
        mav.addObject("exception", e);
        mav.addObject("url", requestURL);
        mav.setViewName(DEFAULT_ERROR_VIEW);
        return mav;
    }


    /**
     * 处理 ServiceException 异常
     */
 /*   @ExceptionHandler(ServiceException.class)
    public Result handleServiceException(ServiceException e){
        Result result = Results.failure(e.getCode(), e.getMessage());
        result.setStatus(HttpStatus.BAD_REQUEST.value());
        logger.info("ServiceException[code: {}, message: {}]", e.getCode(), e.getMessage());
        return result;
    }*/

    /**
     * 处理 AuthorityException 异常
     */
  /*  @ExceptionHandler(AuthorityException.class)
    public Result handleAuthorityException(AuthorityException e){
        Result result = Results.failure(BaseEnums.FORBIDDEN.code(), BaseEnums.FORBIDDEN.desc());
        result.setStatus(HttpStatus.FORBIDDEN.value());
        logger.info("AuthorityException[code: {}, message: {}]", e.getCode(), e.getMessage());
        return result;
    }*/

    /**
     * 处理 NoHandlerFoundException 异常. <br/>
     * 需配置 [spring.mvc.throw-exception-if-no-handler-found=true]
     * 需配置 [spring.resources.add-mappings=false]
     */
  /*  @ExceptionHandler(NoHandlerFoundException.class)
    public Result handleNotFoundException(NoHandlerFoundException e){
        Result result = Results.failure(BaseEnums.NOT_FOUND.code(), BaseEnums.NOT_FOUND.desc());
        result.setStatus(HttpStatus.NOT_FOUND.value());
        logger.info(e.getMessage());
        return result;
    }*/

    /**
     * 处理 BaseException 异常
     */
/*    @ExceptionHandler(BaseException.class)
    public Result handleBaseException(BaseException e){
        Result result = Results.failure(e.getCode(), e.getMessage());
        result.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        log.error("BaseException[code: {}, message: {}]", e.getCode(), e.getMessage(), e);
        return result;
    }*/

    /**
     * 处理 Exception 异常
     */
    /*@ExceptionHandler(Exception.class)
    public Result handleException(Exception e){
        Result result = Results.failure(BaseEnums.ERROR.code(), BaseEnums.ERROR.desc());
        result.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        logger.error(e.getMessage(), e);
        return result;
    }*/
}